<template>
  <div class="mod-config">
    <div v-if="member">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()">
        <el-form-item>
          <el-input v-model="searchData.adName" placeholder="渠道名称"></el-input>
        </el-form-item>
        <el-form-item label="渠道分类：">
          <el-select
            style="width:150px;"
            v-model="searchData.channelId"
            placeholder="请选择"
          >
            <el-option v-for="item in channelList" :key="item.id" :label="item.channelName"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期和时间范围：">
          <el-select
            style="width:150px;"
            @change="dateChanged"
            v-model="searchData.currentDate"
            placeholder="请选择"
          >
            <el-option v-for="item in dateSelect" :key="item" :label="item" :value="item"></el-option>
          </el-select>
          <template v-if="showDatePicker">
            <el-date-picker
              style="width:220px;"
              v-model="searchData.startDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="开始时间"
            ></el-date-picker>
            ~
            <el-date-picker
              style="width:220px;"
              v-model="searchData.endDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="结束时间"
            ></el-date-picker>
          </template>
          <el-button @click="search()">查询</el-button>
          <el-button type="primary" @click="download()" :loading="downloading">下载</el-button>
        </el-form-item>
      </el-form>
      <div class="tableTitle">投放总览</div>
      <el-table
        :data="dataList1"
        border
        v-loading="dataListLoading1"
        style="width: 100%;"
      >
        <el-table-column prop="countName" header-align="center" align="center" label="统计项"></el-table-column>
        <el-table-column prop="visits" header-align="center" align="center" label="访问次数"></el-table-column>
        <el-table-column prop="uv" header-align="center" align="center" label="访问人数"></el-table-column>
        <el-table-column prop="submitFormCount" header-align="center" align="center" label="提交表单人数"></el-table-column>
        <el-table-column prop="userRegistrationNum" header-align="center" align="center"
                         label="新增注册用户"></el-table-column>
        <el-table-column prop="memberRegistrationNum" header-align="center" align="center"
                         label="新增会员用户"></el-table-column>
        <el-table-column prop="userRegisNumConversion" header-align="center" align="center"
                         label="注册转化率"></el-table-column>
        <el-table-column prop="memberRegisNumConversion" header-align="center" align="center"
                         label="会员转化率"></el-table-column>
      </el-table>
      <div class="tableTitle">投放数据</div>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        style="width: 100%;"
        @selection-change="selectionChangeHandle"
        ref="multipleTable"
      >
        <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column prop="name" header-align="center" align="center" label="投放渠道"></el-table-column>
        <el-table-column prop="channelName" header-align="center" align="center" label="渠道分类"></el-table-column>
        <el-table-column prop="visits" header-align="center" align="center" label="访问次数"></el-table-column>
        <el-table-column prop="uv" header-align="center" align="center" label="访问人数"></el-table-column>
        <el-table-column prop="submitFormCount" header-align="center" align="center" label="提交表单人数"></el-table-column>
        <el-table-column prop="userRegistrationNum" header-align="center" align="center"
                         label="新增注册用户"></el-table-column>
        <el-table-column prop="memberRegistrationNum" header-align="center" align="center"
                         label="新增会员用户"></el-table-column>
        <el-table-column prop="userRegisNumConversion" header-align="center" align="center"
                         label="注册转化率"></el-table-column>
        <el-table-column prop="memberRegisNumConversion" header-align="center" align="center"
                         label="会员转化率"></el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
  import treeTable from '@/components/TreeTable'

  export default {
    data() {
      return {
        downloading: false,
        isselect: true,
        islock: true,
        beforeSelect: [],
        channelList: [],
        dataList1: [],
        member: true,
        visibleIntegralList: false,
        dataForm: {
          channelType: null,
          channelName: ''
        },
        dataListSelections: [],
        searchData: {
          currentDate: "昨日",
          startDate: "",
          endDate: "",
          channelId: null
        },
        dataList: [],
        dataListLoading: false,
        dataListLoading1: false,
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        value3: '',
        value4: '',
        dateSelect: [
          "昨日",
          "本周",
          "上周",
          '本月',
          "最近30天",
          "上月",
          "自定义"
        ],
        showDatePicker: false,
        datePickerOptions: {
          disabledDate(time) {
            return (
              time.getTime() > Date.now() ||
              time.getTime() < Date.now() - 30 * 24 * 60 * 60 * 1000
            );
          }
        }
      }
    },
    components: {treeTable},
    mounted() {
      let obj = {
        preDay: 1,
        day: 0
      };
      let timeDate = this.getDateData(obj);
      this.searchData.startDate = timeDate.startDate;
      this.searchData.endDate = timeDate.endDate;
    },
    activated() {
      this.getDataList()
      this.getChannelList()
    },
    methods: {
      //时间select change事件
      dateChanged(val) {
        let obj = {};
        if (val === "昨日") {
          obj.preDay = 1;
          obj.day = 0;
        } else if (val === "本周") {
          let num = new Date().getDay();
          if (num === 0) {
            obj.preDay = 6;
            obj.day = 6;
          } else {
            obj.preDay = num - 1;
            obj.day = 6;
          }
        } else if (val === "上周") {
          let num = new Date().getDay() === 0 ? 7 : new Date().getDay();
          obj.preDay = num + 6;
          obj.day = 6;
        } else if (val === "本月") {
          let num = new Date().getDate();
          obj.preDay = num - 1;
          obj.day = num - 1;
        } else if (val === "最近30天") {
          obj.preDay = 29;
          obj.day = 29;
        } else if (val === "上月") {
          let date = new Date();
          let month = date.getMonth() - 1;
          date.setMonth(month + 1);
          date.setDate(0);
          let monthNum = date.getDate();
          let num = monthNum + new Date().getDate();
          obj.preDay = num - 1;
          obj.day = monthNum - 1;
        }

        if (val === "自定义") {
          this.searchData.startDate = "";
          this.searchData.endDate = "";
          this.showDatePicker = true;
          return;
        } else {
          let timeDate = this.getDateData(obj);
          console.log("timeDate====>", timeDate);
          this.searchData.startDate = timeDate.startDate;
          console.log("this.searchData.endDate====>", timeDate.endDate);
          this.searchData.endDate = timeDate.endDate;
          // if (val === "本周" || val === "最近30天") {
          //   this.searchData.endDate = new Date();
          // } else {
          //   this.searchData.endDate = timeDate.endDate;
          // }
        }
        this.showDatePicker = false;
      },
      // 多选
      selectionChangeHandle(val) {
        let spliceindex = []
        if (this.islock&&(this.beforeSelect.length > val.length)) {
          this.beforeSelect.map((item, index) => {
            let have = false
            let valindex = 0
            while(valindex<val.length) {
              if(val[valindex].name == item.name){
                have = true
                return
              }
              valindex++
            }
            if(!have) {
              spliceindex.push(item.name)
            }
          })
        }
        if (spliceindex.length>0) {
          let datasel = -1
          this.dataListSelections.map((item, index)=> {
            if(item.name === spliceindex[0]) {
              datasel = index
            }
          })
          if(datasel>-1) {
            this.dataListSelections.splice(datasel, spliceindex.length)
          }
        } else {
          this.dataListSelections = this.unique(this.dataListSelections.concat(val))
        }
        this.beforeSelect = val
        console.log(this.dataListSelections, 999)
        if (this.islock) {
          if(this.dataListSelections.length > 0){
            let visits=0,uv=0,submitFormCount=0,userRegistrationNum=0,memberRegistrationNum=0,userRegisNumConversion=0,memberRegisNumConversion=0
            this.dataListSelections.map((item)=> {
              visits+=item.visits
              uv+=item.uv
              submitFormCount+=item.submitFormCount
              userRegistrationNum+=item.userRegistrationNum
              memberRegistrationNum+=item.memberRegistrationNum
              userRegisNumConversion=(userRegisNumConversion+parseInt(item.userRegisNumConversion)*100)/100
              memberRegisNumConversion=(memberRegisNumConversion+parseInt(item.memberRegisNumConversion)*100)/100
            })
            this.dataList1 = [{countName: '合计', visits,uv,submitFormCount,userRegistrationNum,memberRegistrationNum,userRegisNumConversion: userRegisNumConversion.toFixed(1)+'%',memberRegisNumConversion: memberRegisNumConversion.toFixed(1)+'%'}]
            this.dataListLoading1 = false
            this.isselect = false
          } else {
            // 总揽

            this.dataListLoading1 = true
            let obj = {
              page: this.pageIndex,
              limit: this.pageSize
            };
            obj.fromTimeStr = this.searchData.startDate;
            obj.toTimeStr = this.searchData.endDate;
            obj.adName = this.searchData.adName;
            obj.channelId = this.searchData.channelId;

            this.$http({
              url: this.$http.adornUrl('/market/marketadoverview/getAdOverview'),
              method: 'get',
              params: this.$http.adornParams(obj)
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataList1 = [{countName: '合计', ...data.adOverview}]
              } else {
                this.$message.error(data.msg)
              }
              this.dataListLoading1 = false
            })
            this.dataListLoading1 = false
            this.isselect = false
          }

        }
        this.islock = true
      },
      unique(arr) {
        for (var i = 0; i < arr.length; i++) {
          for (var j = i + 1; j < arr.length; j++) {
            if (arr[i].name == arr[j].name) {         //第一个等同于第二个，splice方法删除第二个
              arr.splice(j, 1);
              j--;
            }
          }
        }
        return arr;
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.islock = false
            this.$refs.multipleTable.toggleRowSelection(row, true, 1);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      getDateData(data) {
        let obj = {};
        obj.startDate = "";
        obj.endDate = "";
        if (data && data.preDay + "") {
          let time = Date.now();
          let startDate = getDateText(time - data.preDay * 24 * 3600 * 1000);
          let endDate = getDateText(
            time - data.preDay * 24 * 3600 * 1000 + data.day * 24 * 3600 * 1000
          );
          obj.startDate = startDate;
          obj.endDate = endDate;
        }

        function getDateText(timeMinutes) {
          let date = new Date(timeMinutes);
          let year = date.getFullYear();
          let month =
            date.getMonth() > 8
              ? date.getMonth() + 1
              : "0" + (date.getMonth() + 1);
          let dayText =
            date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
          console.log(dayText)
          return year + "-" + month + "-" + dayText;
        }

        return obj;
      },
      search() {
        this.pageIndex = 1
        this.dataListSelections = []
        this.getDataList()
      },
      // 获取渠道列表
      getChannelList() {
        let obj = {}
        obj.page = 1
        obj.limit = 100
        this.$http({
          url: this.$http.adornUrl('/market/marketchannel/list'),
          method: 'get',
          params: this.$http.adornParams(obj)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.channelList = [{channelName: '全部', id: null}, ...data.page.list]
          }
        })
      },
      download() {
        this.downloading = true
        let selarr = []
        if (this.dataListSelections.length > 0) {
          this.dataListSelections.map((item) => {
            selarr.push(item.marketAdid)
          })
        }
        let obj = {
          page: this.pageIndex,
          limit: this.pageSize
        };
        obj.fromTimeStr = this.searchData.startDate;
        obj.toTimeStr = this.searchData.endDate;
        obj.adIds = selarr.join(',')
        this.$http({
          url: this.$http.adornUrl("/market/marketad/statisticList/download"),
          method: "get",
          params: this.$http.adornParams(obj),
          headers: {
            "Content-Type": "application/json; application/octet-stream"
          },
          responseType: "arraybuffer"
        }).then(({data}) => {
          this.downloading = false
          const blob = new Blob([data], {type: "application/vnd.ms-excel"});
          const downloadElement = document.createElement("a");
          const href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = "投放数据.xls";
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        });
      },
      // 获取数据列表
      getDataList() {
        this.isselect = true
        this.dataListLoading = true
        this.dataListLoading1 = true
        let obj = {
          page: this.pageIndex,
          limit: this.pageSize
        };
        obj.fromTimeStr = this.searchData.startDate;
        obj.toTimeStr = this.searchData.endDate;
        obj.adName = this.searchData.adName;
        obj.channelId = this.searchData.channelId;
        this.$http({
          url: this.$http.adornUrl('/market/marketad/newMarketAdListWithPage'),
          method: 'get',
          params: this.$http.adornParams(obj)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
            let seemarr = []
            this.dataList.map((item) => {
              this.dataListSelections.map((childitem) => {
                if (item.name === childitem.name) {
                  seemarr.push(item)
                }
              })
            })
            this.beforeSelect = seemarr
            if(seemarr.length>0) {
              this.islock = false
              this.$nextTick(() => {
                this.toggleSelection(seemarr)
              })
            }
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
        if(this.dataListSelections.length <= 0){
          // 总揽
          this.$http({
            url: this.$http.adornUrl('/market/marketadoverview/getAdOverview'),
            method: 'get',
            params: this.$http.adornParams(obj)
          }).then(({data}) => {
            if (this.isselect && data && data.code === 0) {
              this.dataList1 = [{countName: '合计', ...data.adOverview}]
            } else {
              this.$message.error(data.msg)
            }
            this.dataListLoading1 = false
          })
        } else {
          this.dataListLoading1 = false
        }
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      }
    }
  }
</script>
<style>
  .margin_10 {
    margin-bottom: 10px;
  }

  .text_r {
    text-align: right;
    padding-right: 15px;
  }

  .inineBlock {
    display: inline-block;
  }

  img {
    width: 100%;
    height: auto;
  }

  .tableTitle {
    font-size: 16px;
    font-weight: 500;
    margin: 20px 0;
  }
</style>
